package com.hadoop.fs;

import java.io.IOException;
import java.util.StringTokenizer;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Partitioner;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

/**
 * 分区
 * 
 * @author conkeyn
 * 
 */
public class PartitionSort {

	// mapper的输出结果中的3，4类型
	public static class TestPart extends Partitioner<Text, IntWritable> {

		@Override
		// getPartition()的返回值，用于将数据分发到hash后的reduce任务
		//返回值必须小于等job.setNumReduceTasks(2);所设置的值，并且序号以0起计数，
		public int getPartition(Text key, IntWritable value, int arg2) {
			// TODO Auto-generated method stub
			// return Integer.parseInt(key.toString().substring(7)) % 2;
			int reduceId = 0; // 默认为第一个任务
			if (Integer.parseInt(key.toString().substring(7)) > 500) {
				reduceId = 1; // 如果手机号码末几位数，大于500，则将数据分派给第二个任务。
			}
			return reduceId;
		}

	}

	// org.apache.hadoop.mapreduce.Mapper<1,2,3,4>4个参数类型分别是，
	// 1和2为输入类型；
	// 3，4为输出结果时需要指输出类型
	public static class Mapper extends org.apache.hadoop.mapreduce.Mapper<LongWritable, Text, Text, IntWritable> {
		private IntWritable one = new IntWritable(1);
		private Text word = new Text();

		protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
			String line = value.toString();
			String[] arr = line.split(",");
			word.set(arr[0]);
			context.write(word, one);
		}

	}

	// org.apache.hadoop.mapreduce.Reducer<1, 2, 3, 4>，
	// 1和2为输入参数类型，这两个参数需要与mapper的输出结果类型对应（即3和4）；
	// 3，4为reducer的输出结果类型
	public static class Reducer extends org.apache.hadoop.mapreduce.Reducer<Text, IntWritable, Text, IntWritable> {

		protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
			int i = 0;
			for (IntWritable value : values) {
				i++;
			}
			context.write(key, new IntWritable(i));
		}

	}

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		Job job = new Job();
		job.setJarByClass(PartitionSort.class);
		job.setJobName("Word count partition");
		FileInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, new Path(args[1]));
		job.setMapperClass(Mapper.class);
		// job.setCombinerClass(Reducer.class);
		job.setReducerClass(Reducer.class);
		job.setPartitionerClass(TestPart.class);
		job.setNumReduceTasks(2);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		System.exit(job.waitForCompletion(true) ? 0 : 1);
	}
}
